<template>
  <!-- ref 绑定给子组件 -->
  <div class="wrapper" ref="wrapper">
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
  import BScroll from 'better-scroll'

  export default {
    name: 'Scroll',
    props: {
      probeType: {
        type: Number,
        default: 0
      },
      pullUpLoad: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        scroll: null
      }
    },
    computed: {
      isPullUpLoad() {
        // threshold: 滚动距离超过50，才上拉加载；小于不加载
        return this.pullUpLoad ? {threshold: -50} : false
      }
    },
    mounted() {
      // 1. 创建BScroll对象
      this.scroll = new BScroll(this.$refs.wrapper, {
        click: true,
        // 对content及content的子元素DOM改变进行监测，发生改变时，会触发 scroll 的 refresh 方法，重新判断滚动内容(content)的高度，解决网络请求到的数据渲染出来的DOM更新不及时的问题
        observeDOM: true,
        // probeType: 3
        probeType: this.probeType,
        pullUpLoad: this.isPullUpLoad
      })

      // 2. 监听滚动的位置
      if(this.probeType === 2 || this.probeType === 3) {
        this.scroll.on('scroll', position => {
          // console.log(position);
          this.$emit('scroll', position)
        })
      } 

      // 3. 监听scroll滚动到底部，即上拉事件
      if (this.pullUpLoad) {
        this.scroll.on('pullingUp', () => {
          // console.log('上拉加载更多');
          this.$emit('pullingUp')
        })
      }
    },
    methods: {
      scrollTo(x, y, time = 300) {
        this.scroll && this.scroll.scrollTo(x, y, time)
      },
      finishPullUp() {
        this.scroll && this.scroll.finishPullUp()
      },
      getScrollY() {
        return this.scroll ? this.scroll.y : 0
      },
      refresh() {
        this.scroll && this.scroll.refresh()
      }
    }
  }
</script>

<style scoped>

</style>